﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace System
{
	public class MapPlot
	{
		V3G center;
		double zoom;

		Bitmap bmp;
		Graphics G;

		public MapPlot(V3G c, double z)
		{
			center = c;
			zoom = z;
		}
		public void CreateBMP(int width, int height)
		{
			bmp = new Bitmap(width, height);
			G = Graphics.FromImage(bmp);
			G.Clear(Color.White);
		}
		public void Save(string fn)
		{
			bmp.Save(fn);
		}
		Point GetPoint(Graphics G, V3G Point)
		{
			double h = G.VisibleClipBounds.Height;
			double w = G.VisibleClipBounds.Width;
			V3D X = center.GetLocalDirection(Point) / zoom * (h / 2);
			return new Point((int)(w / 2 + X.X), (int)(h / 2 - X.Y));
		}
		public void DrawLine(Graphics G, V3G Point1, V3G Point2)
		{
			G.DrawLine(Pens.Black, GetPoint(G, Point1), GetPoint(G, Point2));
		}
		public void DrawStrip(V3G[] Points)
		{
			Point[] pts = new Point[Points.Length];
			for (int i = 0; i < Points.Length; i++)
				pts[i] = GetPoint(G, Points[i]);
			G.DrawLines(Pens.Black, pts);
		}
		public void DrawSign(Graphics G, V3G Pt)
		{
			Point P1 = GetPoint(G, Pt);
			Point P2 = new Point(P1.X, P1.Y - 1);
			G.DrawLine(Pens.Black, P1, P2);
		}

		public delegate Color PlotColorEQ(double[,] Data, int X, int Y);

		public static Color HeightEQ(double[,] Data, int X, int Y)
		{
			double V = Data[X, Y];
			Color C = Color.Blue;
			if (V > -200)
			{
				if (V < 200)
					C = MathWin32.ColorGrad(Color.Green, Color.Yellow, (V+200) / 400);
				else if (V < 2000)
					C = MathWin32.ColorGrad(Color.Yellow, Color.Brown, (V - 200) / 1800);
			}
			return C;
		}

		public void Plot(Bitmap B, double[,] Data, PlotColorEQ ColorEQ)
		{
			int W = Data.GetLength(0);
			int H = Data.GetLength(1);
			BitmapData BD = B.LockBits(new Rectangle(0, 0, W, H), ImageLockMode.ReadOnly, B.PixelFormat);
			int PS = 4;
			for (int y = 0; y < H; y++)
			{
				int rowa = BD.Scan0.ToInt32() + y * BD.Stride;

				for (int x = 0; x < W; x++)
				{
					IntPtr P = new IntPtr(rowa + PS * x);
					Color c = ColorEQ(Data, x, y);
					byte[] C = BitConverter.GetBytes(c.ToArgb());
					Marshal.Copy(C, 0, P, 4);
				}
			}
			B.UnlockBits(BD);
		}
	}
}